import tensorflow as tf  
from tensorflow.keras import layers, models, datasets, losses, optimizers, metrics  
  
# 设置随机种子以确保结果的可重复性  
tf.random.set_seed(42)  
  
# 加载数据集  
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()  
  
# 归一化像素值到0到1之间  
train_images, test_images = train_images / 255.0, test_images / 255.0  
  
# 构建CNN模型  
model = models.Sequential()  
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))  # 卷积层1  
model.add(layers.MaxPoolinwg2D((2, 2)))  # 池化层1  
model.add(layers.Conv2D(64, (3, 3), activation='relu'))  # 卷积层2  
model.add(layers.MaxPooling2D((2, 2)))  # 池化层2  
model.add(layers.Conv2D(64, (3, 3), activation='relu'))  # 卷积层3  
model.add(layers.Flatten())  # 展平层  
model.add(layers.Dense(64, activation='relu'))  # 全连接层1  
model.add(layers.Dense(10))  # 输出层，10个类别  
  
# 编译模型  
model.compile(optimizer=optimizers.Adam(),  
              loss=losses.SparseCategoricalCrossentropy(from_logits=True),  
              metrics=['accuracy'])  
  
# 训练模型  
history = model.fit(train_images, train_labels, epochs=10,   
                    validation_data=(test_images, test_labels))  
  
# 评估模型  
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)  
print('\nTest accuracy:', test_acc)